<?php

class Ga_Image_Image {

    /**
     * make fileName for resized image, prepare folder
     * @param string $configName - section in application.ini - 'blog', 'album'...
     * @param string $sizeName - subsection in application.ini - 'original', 'thumb'...
     * @param array $data - data for substitution in filepath and filename, keys - 'id', 'user_id'...
     * @return array - incoming $data with filePath, longName, fileName, width, height and some other keys
     */
    public function getImageConfig($configName, $sizeName, $data)
    {
        if (empty($configName) || empty($sizeName)) return $data;

        // get settings
        $appConfig = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('config');
        $config    = $appConfig->image->$configName;

        // make subpath
        $pathArr = array(
            'prefix' => realpath($appConfig->image->pathPrefix),
            'path' => $config->path,
            'sizes' => $config->subpath->sizes,
            'idsub' => $config->subpath->id,
        );
        $pathFull = str_replace('//', '/', implode('/', $pathArr));
        $nameArr  = array(
            'idsub' => $config->subpath->id,
            'name' => $config->name,
        );
        $nameFull = str_replace('//', '/', implode('/', $nameArr));

        $data['sizeName']  = $sizeName;
        $data['width']     = $config->sizes->$sizeName->width;
        $data['height']    = $config->sizes->$sizeName->height;
        $data['abcdfghij'] = str_pad($data['id'], 9, '0', STR_PAD_LEFT);
        $data['abc']       = substr($data['abcdfghij'], 0, 3);
        $data['dfg']       = substr($data['abcdfghij'], 3, 3);
        foreach ($data as $k => $v) {
            $pathFull = str_replace('{' . $k . '}', $v, $pathFull);
            $nameFull = str_replace('{' . $k . '}', $v, $nameFull);
        }

        // create path if no exists
        if (!is_dir($pathFull)) {
            $dirs     = explode('/', $pathFull);
            $pathFull = '';
            foreach ($dirs as $dir) {
                if (!empty($dir)) {
                    $pathFull .= $dir . '/';
                    if (!is_dir($pathFull)) {
                        if (!mkdir($pathFull) || !chmod($pathFull, 0777))
                                return false;
                    }
                }
            }
        }
        $data['filePath'] = $pathFull . '/';
        $data['longName'] = $nameFull;

        // make full filename
        $fileName = $config->name;
        foreach ($data as $k => $v) {
            $fileName         = str_replace('{' . $k . '}', $v, $fileName);
        }
        $data['fileName'] = $fileName;

        return $data;
    }

}
